# 掘金
import requests
import json
import time
import os
from tinydb import TinyDB, Query
from urllib.parse import quote, unquote


urlValueJueJin = 'https://api.juejin.cn/content_api/v1/article/query_list?aid=2608&uuid=7098966658006140449&spider=0'
fileName = 'default.json'

def loadData(url):
    headers = {
        "content-type": "application/json",
        "user-agent": "Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/113.0.0.0 Safari/537.36",
        "x-secsdk-csrf-token": "000100000001127b725792493486649386ff7e8a38df3e371049d8143a38417fbce498861e8f17806a861c68a960"
    }
    data = {"user_id":"1574156384091320","sort_type":2,"cursor":"0"}
    respose = requests.post(url=urlValueJueJin,headers=headers,data=json.dumps(data).encode("utf-8"))
    resultData = respose.json()
    
    print(resultData)
    if resultData['err_no'] == 0 and resultData['err_msg'] == 'success':
        firstData = resultData['data'];
        arr_data = []
        selectItem = {};
        for item in firstData:
            itemID = item['article_id']
            titleValue = item['article_info']['title']
            brief_content = item['article_info']['brief_content']
            cover_image = item['article_info']['cover_image']
            ctime = item['article_info']['ctime']
            createTime = transformTime(ctime)
            resultValue = {
                'itemID': itemID,
                'title': titleValue,
                'brief_content': brief_content,
                'cover_image': cover_image,
                'createTime': createTime,
            }
            insertItem(resultValue)
            
        
        
        if 'title' in selectItem:
            print(selectItem)
    else:
        print('接口出现异常')

def transformTime(timeString):
   
    now = int(timeString)
    timeArray = time.localtime(now)
    otherStyleTime = time.strftime("%Y-%m-%d %H:%M:%S", timeArray)
    return otherStyleTime


def insertItem(item):
    db = TinyDB(fileName)
    table = db.table('juejin')
    juejin = Query()
    res = table.search(juejin.itemID == item['itemID'])
    print(item['title'] + ': https://juejin.cn/post/' +item['itemID'])
    # if len(res) == 0:
    #     table.insert(item)
        # dingdingTalk(item['title'] + ': https://juejin.cn/post/' +item['itemID'])
    # else:
    #     print('已存在')
        
# 钉钉机器人的调用
def dingdingTalk(msg):
    HEADERS = {"Content-Type": "application/json;charset=utf-8"}
    key = "e9b59afdcad471cd70b8e4016f2752a03084d66c34abea961f2ebf8a3d785a30"
    url = "https://oapi.dingtalk.com/robot/send?access_token=%s" % key
    data_info = {
        "msgtype": "text",
        "text": {
            # "content": "Log: \n" + msg
            "content": msg
        },
        "isAtAll": True
    }

    value = json.dumps(data_info)
    response = requests.post(url, data=value, headers=HEADERS)

def notificationToken(titleMsg, message):
    # tkoen = 'WwuUQD5ZNv7Aq9A67AswCN'#晓粉的
    tkoen = 'CM3QdttP2tJrGSSJ9ybEqS'  # 我的
    first = quote(titleMsg, 'utf-8')
    second = quote(message, 'utf-8')
    nowTmp = 'https://api.day.app/{}/{}/{}'.format(tkoen, first, second)
    res = requests.post(nowTmp)

    if res.json()['code'] == 200:
        print('发送成功')
    else:
        print(res.text)
 
    
loadData(urlValueJueJin)
